<script lang="ts" setup>
import { inject, onMounted, provide, ref, toRefs } from 'vue';

import { ElArrowDown } from '@vben/icons';

import {
  ElButton,
  ElDialog,
  ElDivider,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElIcon,
  ElMessage,
  ElMessageBox,
  ElPopover,
} from 'element-plus';

import { StyleLibrary } from '#/components/scene-editor';
import { usePublicStore, useSceneStore } from '#/store';

import { PropertyContent } from './content';

const props = defineProps({
  isLayerPropertyDialogShow: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(['closeLayerPropertyDialog', 'sendRenderType']);
const sceneStore = useSceneStore();
const publicStore = usePublicStore();

const isConfirmBtnAval = ref(true);
const currentRenderType = ref('');
const refreshKey = ref(0);
const selectedLayer = inject('currentSelectedLayer') as any;
const contentRef = ref(null as any);
const { isLayerPropertyDialogShow } = toRefs(props);
// 需要一个区分于对话框显示的变量来控制对话框内子组件显示，否则对话框的销毁会阻塞子组件的销毁（生命周期无法捕获）
const isLayerPropertyContentDialogShow = ref(true);
const isStyleLibraryShow = ref(false);
const currentTab = ref(
  selectedLayer.value.organizationType === 'singleLayer' ? '符号化' : '动画',
);
const currentSource = ref();
const isMouseDown = ref(false);
const isDragging = ref(false);
provide('isDragging', isDragging);

const closeThisDialog = () => {
  emit('closeLayerPropertyDialog');
  isLayerPropertyContentDialogShow.value = false;
};

const confirmEditLayerProperty = () => {
  // 制图渲染
  if (currentTab.value === '符号化') {
    if (
      [
        'gradualValueRender',
        'hierarchicalRender',
        'uniqueValueRender',
      ].includes(currentRenderType.value)
    ) {
      if (publicStore.RenderOptions.renderField) {
        emit('sendRenderType', currentRenderType.value);
        closeThisDialog();
      } else {
        ElMessage.warning('请先选择字段');
      }
    } else if (currentRenderType.value === 'multiBandRasterRender') {
      if (publicStore.RenderOptions.bandList.length === 3) {
        emit('sendRenderType', currentRenderType.value);
        closeThisDialog();
      } else {
        ElMessage.warning('请先完善波段信息');
      }
    } else {
      if (
        currentRenderType.value === 'cluster' &&
        selectedLayer.value.renderType[1] !== 'cluster'
      ) {
        const clusterSource = sceneStore.currentSceneConfig.sources.find(
          (item: any) =>
            item.sourceId === `${currentSource.value.sourceId}_cluster`,
        );
        if (clusterSource) {
          ElMessage.error('请勿重复对同一图层添加聚合图!');
        } else {
          ElMessageBox.confirm(
            `聚合图将生成新的带有聚合属性的数据源${currentSource.value.sourceName}_cluster，是否继续?`,
            '提示',
            {
              confirmButtonText: '继续',
              cancelButtonText: '取消',
              type: 'warning',
            },
          )
            .then(() => {
              emit('sendRenderType', currentRenderType.value);
              closeThisDialog();
            })
            .catch(() => {
              ElMessage({
                type: 'info',
                message: '取消渲染',
              });
            });
        }
      } else {
        emit('sendRenderType', currentRenderType.value);
        closeThisDialog();
      }
    }
  }
  // 标注渲染
  else if (currentTab.value === '标注') {
    if (currentRenderType.value === 'textLabel') {
      if (
        (publicStore.LabelOptions.isOpen &&
          publicStore.LabelOptions.renderField) ||
        !publicStore.LabelOptions.isOpen
      ) {
        emit('sendRenderType', currentRenderType.value);
        closeThisDialog();
      } else {
        ElMessage({
          message: '请先选择字段',
          type: 'warning',
        });
      }
    } else {
      if (
        (publicStore.LabelOptions.isOpen &&
          publicStore.LabelOptions.layout['icon-image']) ||
        !publicStore.LabelOptions.isOpen
      ) {
        emit('sendRenderType', currentRenderType.value);
        closeThisDialog();
      } else {
        ElMessage({
          message: '请先选择图标',
          type: 'warning',
        });
      }
    }
  } else {
    // console.log(publicStore.RenderOptions);
    emit('sendRenderType', currentRenderType.value);
    closeThisDialog();
  }
};
const handleTabChange = (tab: string) => {
  currentTab.value = tab;
};
const handleIsConfirmBtnAval = (val: any) => {
  isConfirmBtnAval.value = val;
};
const handleChangeRenderType = (val: string) => {
  currentRenderType.value = val;
};
const getSource = () => {
  sceneStore.currentSceneConfig.sources.forEach((item: any) => {
    if (item.sourceId === selectedLayer.value.source) {
      currentSource.value = item;
    }
  });
};

const handleMouseDown = (_e: Event) => (isMouseDown.value = true);
const handleMouseMove = (_e: Event) => {
  if (isMouseDown.value) isDragging.value = true;
};
const handleMouseUp = () => {
  isMouseDown.value = false;
  isDragging.value = false;
};

const handleApplyStyle = (_renderType: Array<string>) => {
  // console.log(renderType);
  // console.log(contentRef.value);
  refreshKey.value++;

  // if (JSON.stringify(contentRef.value.value) !== JSON.stringify(renderType)) {
  //   // contentRef.value.value = renderType
  //   console.log(1);

  // } else {
  //   // 强制刷新内容组件
  //   console.log(1);
  //   refreshKey.value++
  // }
  // console.log(selectedLayer.value);

  isStyleLibraryShow.value = false;
};
onMounted(() => {
  getSource();
});
</script>
<template>
  <div>
    <ElDialog
      width="650px"
      custom-class="dialog-title"
      v-model="isLayerPropertyDialogShow"
      :title="`图层属性 - ${selectedLayer.name} - ${currentTab}`"
      align-center
      :modal="false"
      :close-on-click-modal="false"
      :draggable="true"
      :destroy-on-close="true"
      @close="closeThisDialog"
      class="dialog-title"
    >
      <template #header="{ titleId, titleClass }">
        <div
          class="my-header"
          @mousedown="handleMouseDown"
          @mouseup="handleMouseUp"
          @mousemove="handleMouseMove"
        >
          <h4 :id="titleId" :class="titleClass" class="font-semibold">
            {{ `图层属性 - ${selectedLayer.name} - ${currentTab}` }}
          </h4>
        </div>
        <ElDivider style="padding: 0; margin: 0" />
      </template>
      <PropertyContent
        ref="contentRef"
        v-if="isLayerPropertyContentDialogShow"
        @change-render-type="handleChangeRenderType"
        @change-tab="handleTabChange"
        @un-avalible-c-btn="handleIsConfirmBtnAval"
        :key="refreshKey"
      />
      <template #footer>
        <div class="dialog-footer">
          <span class="dialog-footer-left">
            <ElPopover
              placement="right-end"
              :width="525"
              :visible="isStyleLibraryShow"
              :popper-style="{ padding: '0px' }"
              v-if="currentTab === '符号化'"
            >
              <template #default>
                <StyleLibrary
                  v-if="isStyleLibraryShow"
                  @close-style-library="isStyleLibraryShow = false"
                  @apply-style="handleApplyStyle"
                />
              </template>
              <template #reference>
                <ElDropdown placement="top-start" trigger="click">
                  <ElButton class="mybtn">
                    样式<ElIcon><ElArrowDown /></ElIcon>
                  </ElButton>
                  <template #dropdown>
                    <ElDropdownMenu>
                      <ElDropdownItem
                        @click.stop="isStyleLibraryShow = !isStyleLibraryShow"
                      >
                        <ElIcon size="15">
                          <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-tuichu" />
                          </svg>
                        </ElIcon>
                        从样式库加载...
                      </ElDropdownItem>
                      <ElDropdownItem>
                        <ElIcon size="15">
                          <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-baocun" />
                          </svg>
                        </ElIcon>
                        保存到样式库
                      </ElDropdownItem>
                    </ElDropdownMenu>
                  </template>
                </ElDropdown>
              </template>
            </ElPopover>
          </span>
          <span class="dialog-footer-right">
            <ElButton
              class="mybtn"
              type="primary"
              @click="confirmEditLayerProperty"
              :disabled="!isConfirmBtnAval"
            >
              {{ currentTab === '符号化' ? '渲染' : '应用' }}
            </ElButton>
            <ElButton class="mybtn" @click="closeThisDialog">退出</ElButton>
          </span>
        </div>
      </template>
    </ElDialog>
  </div>
</template>
<style scoped>
.dialog-footer {
  display: flex;

  .dialog-footer-left {
    margin-right: auto;
    margin-left: 10px;
  }

  .dialog-footer-right button:first-child {
    margin-right: 10px;
  }
}

/* :deep(.el-dialog__header) {
  padding: 0px;
  margin-right: 0px;
} */

.my-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  height: 55px;
  padding-top: 10px;
  padding-bottom: 5px;
  padding-left: 20px;
  font-size: 30px;
}

:deep(.el-dialog) {
  /* background-color: azure; */
  height: auto;
  border-radius: 20px;
  box-shadow: 0 0 50px rgb(0 0 0 / 50%);
}

.mybtn {
  width: 80px;
  height: 30px;
  font-weight: bolder;
  letter-spacing: 1px;
  border-radius: 3px;
}

:deep(.dialog-title .el-dialog__header) {
  padding: 0;
  margin-right: 0;
  background-color: #aac4dc;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;

  .el-dialog__title {
    align-items: center;
    justify-content: center;
    color: #000;
  }

  .el-dialog__headerbtn .el-dialog__close {
    align-items: center;
    justify-content: center;
    color: #747474;
  }
}
</style>
